//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import React, { useEffect, useState } from "react";
import type { AdminPermInfo } from '@/api/admin_auth';
import type { RoadmapInfo } from "@/api/roadmap";
import { ROADMAP_OWNER_ADMIN } from "@/api/roadmap";
import type { ListParam } from "@/api/roadmap_admin";
import { list as list_roadmap, get as get_roadmap, TagInfo, list_tag } from "@/api/roadmap_admin";
import { get_admin_session, get_admin_perm } from '@/api/admin_auth';
import { request } from "@/utils/request";
import { Button, Card, Form, Input, List, Select, Switch } from "antd";
import { PlusOutlined } from "@ant-design/icons";
import EditRoadmapModal from "./components/EditRoadmapModal";
import RoadmapCard from "./components/RoadmapCard";

const PAGE_SIZE = 24;

const RoadmapAdminList = () => {
    const [permInfo, setPermInfo] = useState<AdminPermInfo | null>(null);

    const [listParam, setListParam] = useState<ListParam>({
        filter_by_owner: false,
        owner_type: 0,
        filter_by_owner_user_id: false,
        owner_user_id: "",
        filter_by_keyword: false,
        keyword: "",
        filter_by_tag: false,
        tag: "",
    });
    const [pubState, setPubState] = useState(false);
    const [roadmapList, setRoadmapList] = useState<RoadmapInfo[]>([]);
    const [totalCount, setTotalCount] = useState(0);
    const [curPage, setCurPage] = useState(0);

    const [tagInfoList, setTagInfoList] = useState<TagInfo[]>([]);

    const [showAddModal, setShowAddModal] = useState(false);

    const loadRoadmapList = async () => {
        const sessionId = await get_admin_session();
        const res = await request(list_roadmap({
            session_id: sessionId,
            list_param: listParam,
            filter_by_pub_state: pubState,
            pub_state: pubState,
            offset: curPage * PAGE_SIZE,
            limit: PAGE_SIZE,
        }));
        setRoadmapList(res.roadmap_list);
        setTotalCount(res.total_count);
    };

    const loadTagInfoList = async () => {
        const sessionId = await get_admin_session();
        const res = await request(list_tag({
            session_id: sessionId,
        }));
        setTagInfoList(res.tag_list);
    };

    const onUpdate = async (roadmapId: string) => {
        const tmpList = roadmapList.slice();
        const index = tmpList.findIndex(item => item.roadmap_id == roadmapId);
        if (index == -1) {
            return;
        }
        const sessionId = await get_admin_session();
        const res = await request(get_roadmap({
            session_id: sessionId,
            roadmap_id: roadmapId,
        }));
        tmpList[index] = res.roadmap;
        setRoadmapList(tmpList);
    };

    useEffect(() => {
        loadTagInfoList();
        get_admin_perm().then(res => setPermInfo(res));
    }, []);


    useEffect(() => {
        loadRoadmapList();
    }, [curPage, listParam, pubState]);

    return (
        <Card title="成长路线图" bodyStyle={{ height: "calc(100vh - 90px)", overflowY: "scroll" }}
            extra={
                <Form layout="inline">
                    <Form.Item label="筛选">
                        <Select style={{ width: "100px" }}
                            value={listParam.filter_by_owner ? "official" : "all"} onChange={value => {
                                if (value == "official") {
                                    setListParam({
                                        ...listParam,
                                        filter_by_owner: true,
                                        owner_type: ROADMAP_OWNER_ADMIN,
                                    });
                                } else if (value == "all") {
                                    setListParam({
                                        ...listParam,
                                        filter_by_owner: false,
                                        owner_type: 0,
                                    });
                                }
                            }}>
                            <Select.Option value="official">官方</Select.Option>
                            <Select.Option value="all">全部</Select.Option>
                        </Select>
                    </Form.Item>
                    <Form.Item label="发布状态">
                        <Switch checked={pubState} onChange={checked => setPubState(checked)} size="small" />
                    </Form.Item>
                    <Form.Item label="过滤关键词">
                        <Input value={listParam.keyword} onChange={e => {
                            e.stopPropagation();
                            e.preventDefault();
                            setListParam({
                                ...listParam,
                                filter_by_keyword: e.target.value.trim() != "",
                                keyword: e.target.value.trim(),
                            });
                        }} allowClear />
                    </Form.Item>
                    <Form.Item>
                        <Button type="primary" icon={<PlusOutlined />} onClick={e => {
                            e.stopPropagation();
                            e.preventDefault();
                            setShowAddModal(true);
                        }} disabled={!(permInfo?.roadmap_perm.create ?? false)}>增加路线图</Button>
                    </Form.Item>
                </Form>
            }>
            {permInfo != null && (
                <List rowKey="roadmap_id" dataSource={roadmapList} grid={{ gutter: 16 }}
                    pagination={{ total: totalCount, current: curPage + 1, pageSize: PAGE_SIZE, onChange: page => setCurPage(page - 1) }}
                    renderItem={roadmapItem => (
                        <List.Item>
                            <RoadmapCard roadmap={roadmapItem} permInfo={permInfo} tagInfoList={tagInfoList}
                                onChange={() => onUpdate(roadmapItem.roadmap_id)}
                                onRemove={() => loadRoadmapList()} />
                        </List.Item>
                    )} />
            )}

            {showAddModal == true && (
                <EditRoadmapModal onOk={() => {
                    setListParam({
                        filter_by_owner: false,
                        owner_type: 0,
                        filter_by_owner_user_id: false,
                        owner_user_id: "",
                        filter_by_keyword: false,
                        keyword: "",
                        filter_by_tag: false,
                        tag: "",
                    });
                    setPubState(false);
                    setCurPage(0);
                    setShowAddModal(false);
                }} onCancel={() => setShowAddModal(false)} />
            )}
        </Card>
    );
};

export default RoadmapAdminList;